package lvjia.site.ai;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class kimiapi {
    private static final String ENDPOINT = "https://api.moonshot.cn/v1/chat/completions";
    private static final String AUTH_HEADER_NAME = "Authorization";
    private static final String BEARER_PREFIX = "Bearer ";
    public String executeRequest(String userMessage,String key) {
        String model = "moonshot-v1-8k";
        String result = "";

        try {
            URL url = new URL(ENDPOINT);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty(AUTH_HEADER_NAME, BEARER_PREFIX + key);

            String requestBody = """
                      {
                          "model": "%s",
                          "messages": [
                          {
                          "role": "system",
                          "content": "说中文。"
                          },
                              {
                                  "role": "user",
                                  "content":  "%s"
                              }
                          ],
                          "stream": false
                      }
                """.formatted(model, userMessage);

            connection.setDoOutput(true);
            try (OutputStream os = connection.getOutputStream()) {
                os.write(requestBody.getBytes(StandardCharsets.UTF_8));
            }

            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }

                in.close();
                connection.disconnect();

                JsonObject jsonResponse = JsonParser.parseString(content.toString()).getAsJsonObject();
                if (jsonResponse.has("tool_calls")) {
                    JsonObject toolCalls = jsonResponse.getAsJsonArray("tool_calls").get(0).getAsJsonObject();
                    if (toolCalls.getAsJsonObject("function").get("name").getAsString().equals("bing_mc")) {
                        JsonObject arguments = toolCalls.getAsJsonObject("arguments");
                        // 未完工部分

                    }
                }


                JsonObject firstChoice = jsonResponse.getAsJsonArray("choices").get(0).getAsJsonObject();
                String messageContent = firstChoice.getAsJsonObject("message").get("content").getAsString();

                result = new String(messageContent.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);


            }
        } catch (Exception e) {
            result = "key出错，或服务不可用，请联系管理员切换模型或者修正key！";
        }
        return result;
    }
}